﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Field
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class FieldTypesController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IFieldTypesServer _typeServer;
        private readonly IFieldsServer _fieldsServer;
        public FieldTypesController(IMapper mapper, IFieldTypesServer typeServer, IFieldsServer fieldsServer)
        {
            _mapper = mapper;
            _typeServer = typeServer;
            _fieldsServer = fieldsServer;
        }

        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Function("场地类型", null, "site", "../views/Home/site/siteType/index.vue")]
        public async Task<JsonResult> GetTypePage(int pageIndex = 1, int pageSize = 10, string searchaString = "")
        {

            var result = new ApiResult<PageModel<FieldTypesDto>>() { Success = false, Message = "操作失败" };

            Expressionable<FieldTypes> expressionable = new Expressionable<FieldTypes>();


            expressionable.OrIF(!searchaString.IsNullOrWhiteSpace(), u => u.FieldTypeName.Contains(searchaString) || u.Description.Contains(searchaString));

            var data = await _typeServer.QueryPageAsync(expressionable.ToExpression(), null, pageIndex, pageSize);

            result.Data = _mapper.Map<PageModel<FieldTypesDto>>(data);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 添加场地类型
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddTypeInfo([FromBody] FieldTypesDto dto)
        {
            var result = new ApiResult
            {
                Success = false,
                Message = "操作失败"
            };


            if (dto.TypeName.IsNullOrWhiteSpace())
            {
                result.Message = "类型名称不能为空";
                return new JsonResult(result);
            }

            // 2. 检查类型名称是否已存在
            var existingType = await _typeServer.QueryAsync(t => t.FieldTypeName == dto.TypeName);
            if (existingType != null)
            {
                result.Message = "该类型名称已存在";
                return new JsonResult(result);
            }

            var info = _mapper.Map<FieldTypes>(dto);

            // 4. 执行数据库插入
            var addResult = await _typeServer.AddAsync(info);

            // 5. 处理插入结果
            if (addResult > 0)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 修改场地类型
        /// </summary>
        [HttpPut]
        public async Task<JsonResult> UpdateTypeInfo([FromBody] FieldTypesDto dto)
        {
            var result = new ApiResult { Success = false, Message = "操作失败" };

            // 参数校验
            if (dto.id <= 0)
            {
                result.Message = "无效的类型ID";
                return new JsonResult(result);
            }

            if (string.IsNullOrWhiteSpace(dto.TypeName))
            {
                result.Message = "类型名称不能为空";
                return new JsonResult(result);
            }

            // 检查原数据是否存在
            var existingType = await _typeServer.QueryAsync(dto.id);
            if (existingType == null)
            {
                result.Message = "指定的类型不存在";
                return new JsonResult(result);
            }

            // 检查名称是否重复（排除自己）
            var duplicateCheck = await _typeServer.QueryAsync(t =>
                t.FieldTypeName == dto.TypeName &&
                t.FieldTypeID != dto.id);

            if (duplicateCheck != null)
            {
                result.Message = "类型名称已存在";
                return new JsonResult(result);
            }

            // 更新实体
            var updateEntity = _mapper.Map<FieldTypes>(dto);
            updateEntity.FieldTypeID = dto.id; // 确保ID正确映射

            var updateResult = await _typeServer.UpdateAsync(updateEntity);

            result.Success = updateResult;
            result.Message = updateResult ? "修改成功" : "修改失败";


            return new JsonResult(result);
        }

        /// <summary>
        /// 删除场地类型
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<JsonResult> DeleteTypeInfo(int id)
        {
            var result = new ApiResult { Success = false, Message = "操作失败" };

            // 1. 校验ID有效性
            if (id <= 0)
            {
                result.Message = "无效的类型ID";
                return new JsonResult(result);
            }

            // 2. 检查类型是否存在
            var existingType = await _typeServer.QueryAsync(x => x.FieldTypeID == id);
            if (existingType == null)
            {
                result.Message = "指定的场地类型不存在";
                return new JsonResult(result);
            }

            // 3. 检查关联场地数据
            var relatedFields = await _fieldsServer.QueryListAsync(x => x.FieldTypeID == id);
            if (relatedFields != null && relatedFields.Count > 0)
            {
                result.Message = $"存在{relatedFields.Count}个关联场地，禁止删除";
                return new JsonResult(result);
            }

            // 4. 执行物理删除
            var deleteResult = await _typeServer.DeleteAsync(x => x.FieldTypeID == id);

            result.Success = deleteResult > 0;
            result.Message = deleteResult > 0 ? "删除成功" : "删除失败";


            return new JsonResult(result);
        }
    }
}
